package com.ass.zookeeper.config;

import com.ass.zookeeper.base.CustomerSerializer;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class ZkClientConfig {


    @Value("${zookeeper.connect}")
    private String connect;

    @Value("${zookeeper.sessionTimeout}")
    private int sessionTimeout;


    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public ZkClient zkClient(){
        log.info("正在初始化zookeeper客户端");
        //创建zkClient对象
        ZkClient zkClient = new ZkClient(connect, sessionTimeout);
        //序列化zkClient对象
        zkClient.setZkSerializer(new CustomerSerializer());
        log.info("初始化成功zookeeper客户端");
        return zkClient;
    }

    //向zk注册临时序号节点 根节点想要点版本号什么的
//    @PostConstruct
//    public void initZkPath() {
//        ZkClient zkClient = zkClient();
//        boolean exists = ZkUtils.exists(zkClient, ServerPathEnum.SERVER_PARENT_PATH.path);
//        log.info("根节点状态：{}", exists);
//        if (!exists) {
//            ZkUtils.createPersistent(zkClient,
//                    ServerPathEnum.SERVER_PARENT_PATH.path, "root", ServerNodeType.PERSISTENT.createMode);
//        }
//        String path = ServerPathEnum.SERVER_PARENT_PATH.path + "/" + applicationName + ServerNodeType.EPHEMERAL_SEQUENTIAL.prefix;
//        log.info("path:{}", path);
//        ZkUtils.createPersistent(zkClient, path, applicationName, ServerNodeType.EPHEMERAL_SEQUENTIAL.createMode);
//    }


}
